require 'digest/sha1'

class User < ActiveRecord::Base
 
  has_and_belongs_to_many :groups
  
  validates_presence_of :name, :message => "O nome do usuário deve ser informado"
  
  validates_presence_of :email, :message => "O e-mail do usuário deve ser informado"
  validates_uniqueness_of :email, :message => "Desculpe, esse e-mail já está cadastrado"
  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :message => "O e-mail não é valido, por favor digite novamente"

  attr_accessor :pass_confirmation
  attr_accessor :capabilite_ids
  attr_accessor :capabilite_strs
  
  def validate
    if pass and pass_confirmation then
      if pass.length == 0 then
        errors.add(:pass, "A senha do usuário deve ser informado" )
      end
      if pass_confirmation.length == 0 then
        errors.add(:pass_confirmation, "A senha de confirmação do usuário deve ser informado" )
      end
      if pass != pass_confirmation then
        errors.add(:pass, "As senhas não conferem, digite-as novamente." )
      end
    end
  end

  def pass
    @pass
  end
  
  def pass=(pwd)
    @pass = pwd
    create_new_salt
    self.password = User.encrypted_password(self.pass, self.salt)
  end
  
  def self.authenticate(email, password)
    user = self.find_by_email(email)

    if user
      unless user.status then return -1 end
      expected_password = encrypted_password(password, user.salt)
      if user.password != expected_password
        user = nil
      else
        user.get_capabilite  
      end
    end
    return user
  end
  
  def get_capabilite
    ids = []
    groups = self.groups
    for group in groups
      roles = group.roles
      for role in roles
        cids = role.capabilite_ids
        for id in cids
          capabilite = Capabilite.find(id)
          ids.push(capabilite[:acronym]+":"+capabilite[:name])
        end
      end
    end
    self.capabilite_strs = ids
  end  

  def key
    key = Time.now.day.to_s + "/" + Time.now.mon.to_s + "/" + Time.now.year.to_s + "/" + self.email
    Digest::SHA1.hexdigest(key)
  end
  
  def self.check_key(key,email)
    user = User.find_by_email(email)
    if user and !user.status
      key_check = Time.now.day.to_s + "/" + Time.now.mon.to_s + "/" + Time.now.year.to_s + "/" + email    
      if key == Digest::SHA1.hexdigest(key_check) 
        return user 
      else 
        return nil 
      end
    end
  end
  
  private
  
  def self.encrypted_password(password, salt)
    string_to_hash = password + "charliebrow" + salt
    Digest::SHA1.hexdigest(string_to_hash)
  end
  
  def create_new_salt
    self.salt = self.object_id.to_s + rand.to_s
  end

end